package com.chijun.mform.create.dialog;

import android.content.Context;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;

import androidx.annotation.NonNull;

import com.chijun.mform.FormBuilder;
import com.chijun.mform.R;
import com.chijun.mform.create.adapter.InstallPermissionAdapter;
import com.chijun.mform.create.adapter.ShowProcessAdapter;
import com.chijun.mform.create.fragment.FormAddProcessFragment;
import com.chijun.mform.create.mode.FormApprovePerson;
import com.chijun.mform.create.mode.FormApproveProcess;
import com.chijun.mform.create.mode.FormConfig;
import com.chijun.mform.create.mode.FormField;
import com.example.ccj.b.c.custom.tree.IResultTreeDataListener;
import com.example.ccj.b.c.custom.tree.ISelectTreeListener;
import com.example.ccj.b.c.custom.tree.SelectTreeListDataDialog;
import com.example.ccj.b.c.custom.tree.TreeMode;
import com.example.ccj.b.c.dialog.DialogBase;
import com.example.ccj.b.c.recycler.BaseRecycler;
import com.example.ccj.u.LogUtils;
import com.example.ccj.u.NumberUtils;
import com.example.ccj.u.StringUtils;
import com.example.ccj.u.ToastUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * 审批节点设置dialog
 * 点击后返回
 */
public class ProcessInstallDialog extends DialogBase {

    List<FormField> formFieldList;//全部字段
    Map<Long,Integer> formProcessToFieldPermissionList;
    FormApproveProcess approveProcess;
    List<FormField> formField;
    Map<String,FormApprovePerson> selectedPersonMap;
    ShowProcessAdapter.IInstallListener iInstallListener;
    int position;


    /**
     *
     * @param context 上下文
     * @param formFieldList 该表单所有字段列表
     * @param approveProcess 所属审批流程
     * @param formProcessToFieldPermissionList 该审批流程内的审批人对各个字段的权限
     * @param selectedPersonMap 已选择的审批人
     */
    public ProcessInstallDialog(@NonNull Context context,int position,
                                List<FormField> formFieldList,
                                FormApproveProcess approveProcess,
                                Map<Long,Integer> formProcessToFieldPermissionList,
                                Map<String,FormApprovePerson> selectedPersonMap,
                                ShowProcessAdapter.IInstallListener iInstallListener) {
        super(context);
        this.position = position;
        this.formFieldList = formFieldList;


        //将不可设置审批权限的字段类型去掉
        List<Integer> cannotSetPermissionsFieldTypeArray = FormBuilder.CannotSetPermissionsFieldTypeArray;
        if (cannotSetPermissionsFieldTypeArray != null) {
            Iterator<FormField> iterator = formFieldList.iterator();
            while (iterator.hasNext()) {
                FormField next = iterator.next();
                if (cannotSetPermissionsFieldTypeArray.contains(next.getType())) {
                    iterator.remove();
                }
            }
        }
        this.approveProcess = approveProcess;
        this.formProcessToFieldPermissionList = formProcessToFieldPermissionList;
        this.selectedPersonMap = selectedPersonMap;
        this.iInstallListener = iInstallListener;
    }

    @Override
    public void onInit() {
        isCanClose(true);
        setLayout(R.layout.dialog_process_install);
        setAlpha(1f);//透明度
        isCanClose(true);//点击允许关闭
        isShowBackground(false);//不显示背景
        setShowHeightRatio(true);//按比例显示
        setHeightRatio(0.5);//高度显示比例
        showInBottom();//底部弹出
        setFull(true);//是否铺满
        goneTitleLeftImage();

        setTitleCenterText("审批流程设置");
        setTitleRightText("OK").setOnClickListener(V->{
            if (iInstallListener != null) iInstallListener.result();
            dismiss();
        });

        LinearLayout modeLL = findViewById(R.id.dialog_process_install_mode_ll);
        LinearLayout person = findViewById(R.id.dialog_process_install_select_person);
        RadioGroup radioGroup = findViewById(R.id.dialog_process_install_radio);
        BaseRecycler<FormField> fieldBaseRecycler = findViewById(R.id.dialog_process_install_rec);
        RadioButton rBInstallPermission = findViewById(R.id.dialog_process_install_permission);

        //审批节点权限设置
        rBInstallPermission.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if (isChecked) {
                if (formFieldList == null || formFieldList.isEmpty()) ToastUtils.showShort("请先添加表单字段！");
                modeLL.setVisibility(View.GONE);
                fieldBaseRecycler.setVisibility(View.VISIBLE);
            }
        });


        if (position == 0) {
            modeLL.setVisibility(View.GONE);
            radioGroup.setVisibility(View.GONE);
            rBInstallPermission.setChecked(true);
        } else {
            //基础设置
            RadioButton rBProcessPerson = findViewById(R.id.dialog_process_install_process_person);
            rBProcessPerson.setOnCheckedChangeListener((buttonView, isChecked) -> {
                if (isChecked) {
                    modeLL.setVisibility(View.VISIBLE);
                    fieldBaseRecycler.setVisibility(View.GONE);
                }
            });

            rBProcessPerson.setChecked(true);

            //设置审批方式
            LinearLayout duoRenShenPiFangShi = findViewById(R.id.dialog_process_install_shen_pi_fang_shi);
            //依次审批
            RadioButton yiCiShenPi = findViewById(R.id.dialog_process_install_yi_ci);
            if (approveProcess.duoRenShenPiFangShi == FormAddProcessFragment.APPROVAL_MODE_YI_CI_SHEN_PI) yiCiShenPi.setChecked(true);
            yiCiShenPi.setOnCheckedChangeListener((buttonView, isChecked) -> {
                if (isChecked) {
                    approveProcess.duoRenShenPiFangShi = FormAddProcessFragment.APPROVAL_MODE_YI_CI_SHEN_PI;
                }
            });
            //会签
            RadioButton huiQian = findViewById(R.id.dialog_process_install_hui_qian);
            if (approveProcess.duoRenShenPiFangShi == FormAddProcessFragment.APPROVAL_MODE_HUI_QIAN) huiQian.setChecked(true);
            huiQian.setOnCheckedChangeListener((buttonView, isChecked) -> {
                if (isChecked) {
                    approveProcess.duoRenShenPiFangShi = FormAddProcessFragment.APPROVAL_MODE_HUI_QIAN;
                }
            });
            //或签
            RadioButton huoQian = findViewById(R.id.dialog_process_install_huo_qian);
            if (approveProcess.duoRenShenPiFangShi == FormAddProcessFragment.APPROVAL_MODE_HUO_QIAN) huoQian.setChecked(true);
            huoQian.setOnCheckedChangeListener((buttonView, isChecked) -> {
                if (isChecked) {
                    approveProcess.duoRenShenPiFangShi = FormAddProcessFragment.APPROVAL_MODE_HUO_QIAN;
                }
            });

            LinearLayout personNum = findViewById(R.id.dialog_process_install_select_person_num_ll);
            //人员数量
            EditText personNUm = findViewById(R.id.dialog_process_install_person_num);
            personNUm.setText(String.valueOf(approveProcess.personNum));
            personNUm.addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {}
                @Override
                public void afterTextChanged(Editable s) {
                    approveProcess.personNum = NumberUtils.strToInt(String.valueOf(s));
                }
            });

            //设置审批模式为指定人员
            RadioButton zhiDing = findViewById(R.id.dialog_process_install_zhi_ding);
            zhiDing.setOnCheckedChangeListener((buttonView, isChecked) -> {
                if (isChecked) {
                    person.setVisibility(View.VISIBLE);
                    personNum.setVisibility(View.GONE);
                    if (approveProcess.type == FormAddProcessFragment.SHEN_PI_REN_JIE_DIAN) duoRenShenPiFangShi.setVisibility(View.VISIBLE);
                    approveProcess.personType = FormAddProcessFragment.APPROVAL_SELECT_MODE_ZHI_DING;
                }
            });
            //设置审批模式为发起人自选
            RadioButton ziXuan = findViewById(R.id.dialog_process_install_zi_xuan);
            ziXuan.setOnCheckedChangeListener((buttonView, isChecked) -> {
                if (isChecked) {
                    person.setVisibility(View.GONE);
                    personNum.setVisibility(View.VISIBLE);
                    if (approveProcess.type == FormAddProcessFragment.SHEN_PI_REN_JIE_DIAN) duoRenShenPiFangShi.setVisibility(View.VISIBLE);
                    approveProcess.personType = FormAddProcessFragment.APPROVAL_SELECT_MODE_FA_QI_REN_XUAN_ZE;
                }
            });

            //设置审批模式为发起人自己
            RadioButton faQiRen = findViewById(R.id.dialog_process_install_fa_qi_ren);
            faQiRen.setOnCheckedChangeListener((buttonView, isChecked) -> {
                if (isChecked) {
                    person.setVisibility(View.GONE);
                    duoRenShenPiFangShi.setVisibility(View.GONE);
                    personNum.setVisibility(View.GONE);
                    approveProcess.personType = FormAddProcessFragment.APPROVAL_SELECT_MODE_FA_QI_REN_ZI_JI;
                }
            });

            //设置审批人员 默认值 指定人 通过其改变选中事件来改变UI现实
            if (approveProcess.personType == FormAddProcessFragment.APPROVAL_SELECT_MODE_ZHI_DING) zhiDing.setChecked(true);
            //设置审批人员 默认值 自选 通过其改变选中事件来改变UI现实
            if (approveProcess.personType == FormAddProcessFragment.APPROVAL_SELECT_MODE_FA_QI_REN_XUAN_ZE) ziXuan.setChecked(true);
            //设置审批人员 默认值 发起人 通过其改变选中事件来改变UI现实
            if (approveProcess.personType == FormAddProcessFragment.APPROVAL_SELECT_MODE_FA_QI_REN_ZI_JI) faQiRen.setChecked(true);

            //选择人员
            ImageView selectPerson = findViewById(R.id.dialog_process_install_add_person);
            EditText editText = findViewById(R.id.dialog_process_install_person_text);
            String peronNmeSet = getPeronNmeSet();
            if (!StringUtils.isEmpty(peronNmeSet)) editText.setText(peronNmeSet);

            selectPerson.setOnClickListener(v -> {
                //转换人名为文本
                openSelectUserDialog(editText);
            });
        }
        //设置审批人员对每个字段权限的Recycler
        fieldBaseRecycler.setAdapter(formFieldList,new InstallPermissionAdapter(formFieldList,approveProcess,formProcessToFieldPermissionList));
    }


    private void getPerson(String treeViewName,ISelectProcessPerson iSelectProcessPerson,List<String> selectedList,boolean cnSelectBuMen){
        //人员选择dialog
        SelectPersonNewDialog selectPersonNewDialog = new SelectPersonNewDialog(getContext(), treeViewName, selectedList, 0, false, false, new ISelectProcessPerson() {
            @Override
            public void onOver(List<TreeMode> treeModeList) {
                if (iSelectProcessPerson != null) iSelectProcessPerson.onOver(treeModeList);
            }
        });
        selectPersonNewDialog.show();
    }


    /**
     * 打开人员选择界面
     * @param editText 选择完人员回写人员名称控件
     */
    private void openSelectUserDialog(EditText editText) {
        getPerson("选择审批人", new ISelectProcessPerson() {
            @Override
            public void onOver(List<TreeMode> treeModeList) {
                selectedPersonMap.clear();
                for (TreeMode treeMode : treeModeList) {
                    FormApprovePerson formApprovePerson = new FormApprovePerson();
                    formApprovePerson.processId = approveProcess.id;
                    formApprovePerson.personId = treeMode.dataId;
                    formApprovePerson.personName = treeMode.name;
                    selectedPersonMap.put(treeMode.dataId,formApprovePerson);
                }
                editText.setText(getPeronNmeSet());
            }
        },new ArrayList<>(selectedPersonMap.keySet()),false);
    }


    //获取已选择的人员名称文本
    private String getPeronNmeSet(){
        StringBuilder stringBuilder = new StringBuilder();
        for (FormApprovePerson value : selectedPersonMap.values()) {
            stringBuilder.append(value.personName).append(",");
        }
        return stringBuilder.toString();
    }
}
